<?php

namespace app\business\controller;

use app\business\model\store\User as StoreUser;
use think\Session;

/**
 * 商户认证
 * Class Passport
 * @package app\business\controller
 */
class Passport extends Controller
{
    /**
     * 商户后台登录
     * @return array|bool|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $admin_user = Session::get('yoshop_store');
        if (isset($admin_user['user']['user_name']) && $admin_user['user']['user_name'] == 'admin'){
            $model = new StoreUser;
            $user_s = $model->where('user_name','=','admin')
                ->where('business_user_id','=',$this->request->param('user_id'))
                ->find();
            //wxapp 需要重新获取
            $user = [
                'store_user_id'=>$user_s->store_user_id,
                'user_name'=>'admin',
                'business_user_id'=>$user_s->business_user_id,
                'wxapp'=>$admin_user['wxapp']
            ];
            $model->loginState($user);
            $this->redirect('index/index');
        }
        if ($this->request->isAjax()) {
            $model = new StoreUser;
            if ($model->login($this->postData('User'))) {
                return $this->renderSuccess('登录成功', url('index/index'));
            }
            return $this->renderError($model->getError() ?: '登录失败');
        }
        $this->view->engine->layout(false);
        return $this->fetch('login', [
            // 系统版本号
            'version' => get_version(),
            'user_id' => $this->request->param('user_id')
        ]);
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Session::clear('yoshop_store');
        $this->redirect('passport/login');
    }

}
